#include "tlock.h"
namespace tlib
{
TMutex::TMutex()
{
#ifdef WIN32
  ::InitializeCriticalSection(&m_mutex);
#else
  pthread_mutex_init(&m_mutex, NULL);
#endif
}

TMutex::~TMutex()
{
#ifdef WIN32
  ::DeleteCriticalSection(&m_mutex);
#else
  pthread_mutex_destroy(&m_mutex);
#endif
}

bool TMutex::Lock()
{
#ifdef WIN32
  ::EnterCriticalSection(&m_mutex);
  return true;
#else
  return pthread_mutex_lock(&m_mutex) == 0 ? true : false;
#endif
}

bool TMutex::Unlock()
{
#ifdef WIN32
  ::LeaveCriticalSection(&m_mutex);
  return true;
#else
  return pthread_mutex_unlock(&m_mutex) == 0 ? true : false;
#endif
}

bool TMutex::Trylock()
{
#ifdef WIN32
  ::TryEnterCriticalSection(&m_mutex);
  return true;
#else
  return pthread_mutex_trylock(&m_mutex) == 0 ? true : false;
#endif
}

TCondition::TCondition()
{
#ifdef WIN32
  ::InitializeConditionVariable(&m_cond);
#else
  pthread_cond_init(&m_cond, NULL);
#endif
}

TCondition::~TCondition()
{
#ifdef WIN32

#else
  //pthread_cond_destory(&m_cond);
#endif
}

bool TCondition::Wait(TMutex *pLock)
{
#ifdef WIN32
  if (::SleepConditionVariableCS(&m_cond, &(pLock->m_mutex), INFINITE) != 0)
  return false;
#else
  if (pthread_cond_wait(&m_cond, &(pLock->m_mutex)) != 0)
    return false;
#endif
  return true;
}

bool TCondition::Notify()
{
#ifdef WIN32
  ::WakeConditionVariable(&m_cond);
#else
  if (pthread_cond_signal(&m_cond) != 0)
    return false;
#endif
  return true;
}

bool TCondition::NotifyAll()
{
#ifdef WIN32
  ::WakeAllConditionVariable(&m_cond);
#else
  if (pthread_cond_broadcast(&m_cond) != 0)
    return false;
#endif
  return true;
}

TAutoLock::TAutoLock(TMutex *pLock) :
    m_pMutex(pLock), m_bLocked(true)
{
  m_pMutex->Lock();
}

TAutoLock::~TAutoLock()
{
  Unlock();
}

void TAutoLock::Unlock()
{
  if (m_bLocked)
  {
    m_pMutex->Unlock();
    m_bLocked = false;
  }
}
}
